package org.langqiao.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * volatile 保证了可见性，但是没有保证原子性(线程工作内存，刷新到主内存中去)
 * 自增操作是不具备原子性的，包括读取变量的原始值，进行加1操作，写入工作内存
 * @author mingyangyang
 *
 */
public class VolatileTest {
	/*private AtomicInteger inc = new AtomicInteger(0);
	
	public void increase(){
		inc.incrementAndGet();
	}*/
	/*private volatile int inc = 0;
	public synchronized void increase(){
		inc ++;
	}*/
	Lock lock = new ReentrantLock();
	private volatile int inc = 0;
	
	public void increase(){
		lock.lock();
		try {
			inc ++;
		} finally {
			lock.unlock();
		}
	}
	
	public static void main(String[] args) {
		final VolatileTest test = new VolatileTest();
		for(int i=0;i<100;i++){
			new Thread(){
				public void run(){
					for(int j=0;j<1000;j++){
						test.increase();
					}
				}
			}.start();
		}
		//保证前面的线程都执行完
		while(Thread.activeCount()>1){
			//线程让步
			Thread.yield();
		}
		System.out.println(test.inc);
	}
}
